package com.yc.thread.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class TestReadAndWriteLock {
	
	/**
	 * 阅读
	 * @param lock			锁
	 * @param readerName	读者名字
	 */
	public void read(Lock lock, String readerName) {
		lock.lock();
		try {
			System.out.println(readerName + " read start");
			TimeUnit.SECONDS.sleep(1);
			System.out.println(readerName + " read over");
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}
	
	/**
	 * 写
	 * @param lock			锁
	 * @param writerName	作者名称
	 */
	public void write(Lock lock, String writerName) {
		lock.lock();
		try {
			System.out.println(writerName + " write start");
			TimeUnit.SECONDS.sleep(1);
			System.out.println(writerName + " write over");
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}

	public static void main(String[] args) {
		TestReadAndWriteLock tw = new TestReadAndWriteLock();
		ReadWriteLock rw = new ReentrantReadWriteLock();//定义一个读写锁生成器
		
		Lock readLock = rw.readLock();//生成读锁
		Lock writeLock = rw.writeLock();//生成写锁
		
		Lock lock = new ReentrantLock();

		for (int i = 0; i < 3; i++) {//3个作者入场
			final int id = i;
			new Thread(() -> tw.write(writeLock, "作者"+id)).start();
		}
		for (int i = 0; i < 3; i++) {//10个读者入场
			final int id = i;
			new Thread(() -> tw.read(readLock, "读者"+id)).start();
		}


	}

}
